<template>
  <div class="home" :style="{ 'min-height': minHeight }">
    <van-nav-bar title="编辑地址" left-arrow>
      <template #left>
        <Back />
      </template>
    </van-nav-bar>
    <van-address-edit
      :area-list="areaList"
      show-postal
      show-delete
      show-set-default
      show-search-result
      :address-info="addressInfo"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="methods.onSave"
      @delete="methods.onDelete"
    />
  </div>
</template>

<script lang="ts" setup>
import { AddressEditInfo } from 'vant'
import Back from '@/components/Back.vue'
import { areaList } from '@vant/area-data'
import { onMounted, reactive } from 'vue'
import { GET, postFormData } from '@/api'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()

const minHeight = innerHeight + 'px'
let id = ''
const addressInfo = reactive<AddressEditInfo>({
  tel: '',
  name: '',
  city: '',
  county: '',
  province: '',
  areaCode: '',
  isDefault: undefined,
  addressDetail: ''
})

const methods = {
  onSave(info: AddressEditInfo) {
    postFormData({
      url: '/address/edit',
      params: {
        id,
        name: info.name,
        phone: info.tel,
        province: info.province,
        city: info.city,
        district: info.county,
        detail_address: info.addressDetail,
        // area_code: info.areaCode,
        // postal_code: info.postalCode,
        is_default: info.isDefault ? 1 : 0
      }
    })
      .then((res) => {
        if (res.data) {
          showSuccessToast('保存成功')
        } else {
          showFailToast('保存失败')
        }
      })
      .catch((err) => {
        console.error(err)
      })
  },
  getAddress(id) {
    GET({
      url: '/address/detail',
      params: {
        id
      }
    })
      .then((res) => {
        const resData = res.data[0]
        addressInfo.name = resData.user_name
        addressInfo.tel = resData.phone
        addressInfo.province = resData.province
        addressInfo.city = resData.city
        addressInfo.county = resData.district
        addressInfo.addressDetail = resData.detail_address
        // addressInfo.areaCode = resData.areaCode
        // addressInfo.postalCode = resData.postalCode
        addressInfo.isDefault = resData.is_default === 1 ? true : false
      })
      .catch((err) => {
        console.error(err)
      })
  },
  onDelete() {
    postFormData({
      url: '/address/delete',
      params: {
        id
      }
    })
      .then(() => {
        showSuccessToast('删除成功')
        router.go(-1)
      })
      .catch((err) => {
        console.error(err)
      })
  }
}

onMounted(() => {
  id = (route.query.id ?? '') as string
  methods.getAddress(id)
})
</script>

<style lang="less" scoped>
.home {
  background-color: rgb(245, 245, 245);
}
:deep(.van-button--danger) {
  background-color: rgb(12, 52, 186);
  border: 1px solid rgb(12, 52, 186);
}
</style>
